package com.kongwg.java;

import org.junit.Test;

import java.io.*;

/**
 * @author kongwg
 * @create 2020-12-18 21:22
 */
public class OrderStreamTest {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);

            while (true) {
                System.out.println("请输入字符");
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
                    System.out.println("程序结束");
                    break;
                }

                String aCase = data.toUpperCase();
                System.out.println(aCase);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (br != null) {

                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test3() throws FileNotFoundException {
        //打印流
        PrintStream ps = new PrintStream(new FileOutputStream("data.txt"), true);

        if (ps != null) {
            System.setOut(ps);
        }


        for (int i = 0; i <= 255; i++) { // 输出ASCII字符
            System.out.print((char) i);
            if (i % 50 == 0) { // 每50个数据一行
                System.out.println(); // 换行
            }
        }

        ps.close();


    }

    /*
    3. 数据流
    3.1 DataInputStream 和 DataOutputStream
    3.2 作用：用于读取或写出基本数据类型的变量或字符串

    练习：将内存中的字符串、基本数据类型的变量写出到文件中。

    注意：处理异常的话，仍然应该使用try-catch-finally.
     */
    @Test
    public void test2() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("dataO.txt"));

        dos.writeUTF("孔");
        dos.flush();
        dos.writeInt(18);
        dos.flush();
        dos.writeBoolean(false);
        dos.flush();


        dos.close();
    }

    @Test
    public void test4() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("dataO.txt"));

        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();
        System.out.println("name " + name);
        System.out.println("age " + age);
        System.out.println("isMale " + isMale);

        dis.close();
    }
}
